//
//  PictureView.m
//  Leisure
//
//  Created by 王金晶 on 16/3/11.
//  Copyright © 2016年 王金晶. All rights reserved.
//

#import "PictureView.h"
#import <UIImageView+WebCache.h>

@interface PictureView()

@property(nonatomic,strong)NSArray *imageArray;
@end
@implementation PictureView
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

//- (void)dealloc
//{
//    [_timer invalidate];
//    _timer = nil;
//}

- (instancetype)initWithFrame:(CGRect)frame imageArray:(NSMutableArray *)imageArray
{
    self = [super initWithFrame:frame];
    if(self)
    {
        _imageArray = imageArray;
        self.scrollerView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
        //self.scrollerView.backgroundColor = [UIColor cyanColor];
        self.scrollerView.delegate = self;
        _scrollerView.contentSize = CGSizeMake(frame.size.width *(imageArray.count + 2), frame.size.height);
        _scrollerView.bounces = NO;
        _scrollerView.showsHorizontalScrollIndicator = NO;
        _scrollerView.showsVerticalScrollIndicator = NO;
        _scrollerView.pagingEnabled = YES;
        [self addSubview:_scrollerView];
        
        for (int i = 0; i < imageArray.count + 2; i++)
        {
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(i * frame.size.width, 0, frame.size.width, frame.size.height)];
            //第一个imageView 放的是数组里面最后一张图片
            NSInteger index = imageArray.count - 1;
            
            if (i > 0) {
                index = (i - 1) % imageArray.count;
            }
            
            //UIImage *image = [UIImage imageNamed:imageArray[index]];
            //imageView.image = image;
            [imageView sd_setImageWithURL:[NSURL URLWithString:imageArray[index]]];
            [_scrollerView addSubview:imageView];
        }
        //设置scrollView起始位置为第二张（数组里的第一张）
        [_scrollerView setContentOffset:CGPointMake(_scrollerView.frame.size.width, 0) animated:NO];
        
        
        self.pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(frame.size.width - 120, frame.size.height - 30, 150, 30)];
        _pageControl.numberOfPages = imageArray.count;
        //_pageControl.backgroundColor = [UIColor grayColor];
       // _pageControl.alpha = 0.3;
        [self addSubview:_pageControl];
        
        //创建定时器
        //_timer = [NSTimer timerWithTimeInterval:2 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
        _timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
        /*
        //将定时器加到runloop中
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [[NSRunLoop currentRunLoop]addTimer:_timer forMode:NSDefaultRunLoopMode];
            BOOL isrun = NO;
            if (!isrun)
            {
                isrun = [[NSRunLoop currentRunLoop]runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
            }
        });
         */
        
        //添加轻拍手势
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickScrollView:)];
        [_scrollerView addGestureRecognizer:tap];

    }
    return self;
}
- (void)timerAction:(NSTimer *)timer
{
    //定时器执行的方法,每过一秒在当前的偏移量偏移一个scrollerview的宽度
    [self.scrollerView setContentOffset:CGPointMake(_scrollerView.contentOffset.x + _scrollerView.frame.size.width, 0) animated:YES];
    //判断是不是偏移到最后一张(数组的第一张)跳转到前面一张
    if (_scrollerView.contentOffset.x == (_imageArray.count + 1) *_scrollerView.frame.size.width)
    {
        //跳转到第二张(数组第一张)
        [_scrollerView setContentOffset:CGPointMake(_scrollerView.frame.size.width * 1, 0) animated:NO];
        //马上偏移到下一张,避免切换效果
        [_scrollerView setContentOffset:CGPointMake(_scrollerView.frame.size.width * 2, 0) animated:YES];
    }
    //根据当前是第几张 对pagecontroller赋值
    NSInteger index = _scrollerView.contentOffset.x / _scrollerView.frame.size.width;
    if (index == _imageArray.count)
    {
        index = 0;
    }
    _pageControl.currentPage = index;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [_timer performSelector:@selector(setFireDate:) withObject:[NSDate distantPast] afterDelay:2];
    //如果是第一张(数组最后一张)就偏移到倒数第二张
    if (scrollView.contentOffset.x  == 0)
    {
        [scrollView setContentOffset:CGPointMake(scrollView.frame.size.width * _imageArray.count, 0) animated:NO];
    }
    //如果是最后一张(数组第一张)就偏移到第二张
    if (scrollView.contentOffset.x == (_imageArray.count + 1) * scrollView.frame.size.width)
    {
        [scrollView setContentOffset:CGPointMake(scrollView.frame.size.width, 0) animated:NO];
    }
    //给controller赋值
    NSInteger index = scrollView.contentOffset.x / scrollView.frame.size.width - 1;
    _pageControl.currentPage = index;

}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView.dragging) {
        //让用户拖拽的时候停止计时器
        [_timer setFireDate:[NSDate distantFuture]];
    }
}
- (void)clickScrollView:(UITapGestureRecognizer *)tap
{
    if (_delegate && [_delegate respondsToSelector:@selector(clickedScrollViewWithIndex:)])
    {
        [_delegate clickedScrollViewWithIndex:_pageControl.currentPage];
    }
}
@end
